package wyx.utils;


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WFileReader {

    /**
     * 文本文件的绝对路径
     */
    private String filepath;

    /**
     * 资源对象，注意，需要设计一个关闭的方法
     */
    private BufferedReader bufferedReader;

    /**
     * 批次数量，每次从文本文件中提取的数据量
     */
    private Integer batchNum = 1000;


    public WFileReader(String filepath) throws FileNotFoundException {
        this.filepath = filepath;
        this.bufferedReader = new BufferedReader(new FileReader(filepath));

    }

    public WFileReader(String filepath, Integer batchNum) throws FileNotFoundException {
        this.filepath = filepath;
        this.batchNum = batchNum;
        this.bufferedReader = new BufferedReader(new FileReader(filepath));
    }

    /**
     * 分批读取数据，每次读取返回 程度为 batchNum 数量的 List
     * 注意，如果文本文件中没有数据了，那么返回的 list的 长度为0
     * @return
     */
    public List<String> reabBatch() throws IOException {

        final ArrayList<String> list = new ArrayList<>();

        int count = 0;

        while ( true ){
            final String line = bufferedReader.readLine();
            if (line!=null){
                list.add(line);
                count++;
                if (count == batchNum){ // 如果已经读够了 批次数量，则直接把list返回
                    return list;
                }
            }else {  // 如果读到文件末尾了，则直接返回list
                return list;
            }
        }

    }

    public void close() throws IOException {
        this.bufferedReader.close();
    }


    public static void main(String[] args) throws IOException {
        final WFileReader qfFileReader = new WFileReader("D:\\names.txt", 10);

        while (true) {
            final List<String> list = qfFileReader.reabBatch();
            if ((list.size()==0)) {
                System.out.println("finish!");
                return;
            }
            for (String s : list) {
                System.out.println(s);
            }
            System.out.println("==========================");
        }
    }
}